/***************************************************************************
 *   Copyright (C) 2009 by mj   *
 *   mj_dv@web.de   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

// ssu_gui.cpp is a part of the steamserverutil project
// steamserverutil.googlecode.com

#include <QByteArray>
#include <QSettings>
#include <QProcess>
#include <QString>
#include <QInputDialog>
#include <QMessageBox>
#include <QCloseEvent>
#include <QTimer>


#include "ssu_gui.h"
#include "ui_ssu_gui.h"
#include "startServer.h"
#include "about.h"
#include "configure.h"
#include "steamserverutil.h"
#include "installserver.h"
#include "installmani.h"
#include "setwspace.h"
#include "cpmaps.h"

ssu_gui::ssu_gui()
{
    setWindowIcon(QIcon(":/images/ssu_128.png"));

    setupUi(this);

    setCentralWidget(tabWidget);

    util = new steamserverutil();
    server_process = new QProcess(this);
    dbgConsole = new debugConsole(this);
    dbgConsole->add("ssu_gui started ..");

    connect(commandButton, SIGNAL(clicked()), this, SLOT(send_command()));


    createActions();
    readSettings();

}

void ssu_gui::send_command()
{

    QString cmd = commandEdit->text();

    /*if(cmd.isEmpty())
        return;*/

    if(cmd == "ssu_gui::isRunning")
    {
        switch(server_process->state())
        {
            case QProcess::Running:
                serverLog->append(tr("Server is running!"));
                break;
            case QProcess::NotRunning:
                serverLog->append(tr("Server is not running!"));
                break;
            case QProcess::Starting:
                serverLog->append(tr("Server is about to start!"));
                break;
        }
    }
    else
    {
        serverLog->append(tr("Sent command: ") + cmd.toAscii());
        int bytes_sent = server_process->write(cmd.toStdString().c_str(), strlen(cmd.toStdString().c_str()));
        if (bytes_sent == -1)
            serverLog->append(tr("ERROR sending command!"));
        else
            serverLog->append(tr("Bytes sent: %1").arg(bytes_sent));
        read_stdout();
    }

    //commandEdit->clear();

}

void ssu_gui::is_started()
{
    serverLog->append("ssu_gui::is_started()");
}

void ssu_gui::read_stdout()
{
    serverLog->append("ssu_gui::read_stdout()");
    serverLog->append(server_process->readAllStandardOutput().data());
}

void ssu_gui::createActions()
{
    startServerAction->setStatusTip(tr("Start a new server"));
    startServerAction->setShortcut(tr("CTRL+S"));

    connect(startServerAction, SIGNAL(triggered()), this, SLOT(start_server()));

    refreshAction->setStatusTip(tr("Refreshs the Server output"));
    refreshAction->setShortcut(tr("CTRL+R"));

    connect(refreshAction, SIGNAL(triggered()), this, SLOT(refresh_server_ouput()));

    terminateServerAction->setStatusTip(tr("Closes the server sub process"));
    terminateServerAction->setShortcut(tr("CTRL+T"));

    connect(terminateServerAction, SIGNAL(triggered()), this, SLOT(terminateServer()));

    clearOutputAction->setStatusTip(tr("Clears the Server output"));
    clearOutputAction->setShortcut(tr("CTRL+L"));

    connect(clearOutputAction, SIGNAL(triggered()), this, SLOT(clear_server_output()));

    exitAction->setStatusTip(tr("Exit the program"));
    exitAction->setShortcut(tr("CTRL+E"));

    connect(exitAction, SIGNAL(triggered()), qApp, SLOT(closeAllWindows()));

    setWorkspaceAction->setStatusTip(tr("Set the current working directory"));
    setWorkspaceAction->setShortcut(tr("CTRL+W"));
    connect(setWorkspaceAction, SIGNAL(triggered()), this, SLOT(setWorkSpace()));

    configureServersAction->setStatusTip(tr("Configure the Servers"));
    configureServersAction->setShortcut(tr("CTRL+U"));
    connect(configureServersAction, SIGNAL(triggered()), this, SLOT(config()));

    aboutQtAction->setStatusTip(tr("Show the Qt librarys About Box"));

    connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));

    aboutAction->setStatusTip(tr("About ssu_gui"));

    connect(aboutAction, SIGNAL(triggered()), this, SLOT(ab()));

    installServerAction->setStatusTip(tr("Installs a new server"));
    installServerAction->setShortcut(tr("CTRL+N"));

    connect(installServerAction, SIGNAL(triggered()), this, SLOT(install()));

    installManiAction->setStatusTip(tr("Installs Mani Admin plugin into your server"));
    installManiAction->setShortcut(tr("CTRL+M"));

    installQuakeAction->setStatusTip(tr("Installs the quake sound Pack for Mani Admin Plugin into your server"));
    installQuakeAction->setShortcut(tr("CTRL+Q"));

    openDbgConsoleAction->setStatusTip(tr("Opens a Windows where you can see more information about what this program did"));
    openDbgConsoleAction->setShortcut(tr("CTRL+D"));

    connect(installManiAction, SIGNAL(triggered()), this, SLOT(install_mani()));
    connect(installQuakeAction, SIGNAL(triggered()), this, SLOT(install_mani()));
    connect(openDbgConsoleAction, SIGNAL(triggered()), this, SLOT(openDbgConsole()));



    switchLangAction->setStatusTip(tr("Select another Language"));
    switchLangAction->setShortcut(tr("CTRL+L"));

    connect(switchLangAction, SIGNAL(triggered()), this, SLOT(switchLanguage()));

    copyMapsAction->setStatusTip(tr("Copy maps from a folder into the server"));
    copyMapsAction->setShortcut(tr("CTRL+M"));

    connect(copyMapsAction, SIGNAL(triggered()), this, SLOT(copyMaps()));



}

void ssu_gui::start_server()
{
    serverLog->clear();

    startServer *ss = new startServer(this);

    ss->exec();

    if(ss->workdir.isEmpty())
        return; //cancel was clicked

    serverLog->append(ss->command_to_start + "\n" + ss->workdir);


    server_process->setWorkingDirectory(ss->workdir);
    server_process->start(ss->command_to_start);

    connect(server_process, SIGNAL(readyReadStandardOutput()), SLOT(read_stdout()));
    connect(server_process, SIGNAL(started()), this, SLOT(is_started()));

    delete ss;
}

void ssu_gui::refresh_server_ouput()
{
    read_stdout();
}

void ssu_gui::terminateServer()
{
    server_process->write("exit");
    server_process->close();
    server_process->terminate();
    server_process->kill();
}

void ssu_gui::readSettings()
{
    QSettings settings("MJ", "ssu_gui");

    resize(settings.value("size", QSize(500, 500)).toSize());
    if(settings.value("isMaximized").toBool())
        showMaximized();
}

void ssu_gui::writeSettings()
{
    QSettings settings("MJ", "ssu_gui");

    settings.setValue("size", size());
    settings.setValue("isMaximized", isMaximized());

}

void ssu_gui::closeEvent(QCloseEvent *event)
{


    writeSettings();

    terminateServer();
    event->accept();

}

void ssu_gui::ab()
{
    about *a = new about(this);
    a->exec();

    delete a;

    
}

void ssu_gui::clear_server_output()
{
    serverLog->clear();
}

void ssu_gui::config()
{
    configure *c = new configure(this);

    c->exec();

    delete c;
}

void ssu_gui::install()
{
    installServer *inst = new installServer(this);

    inst->exec();

    delete inst;
}

void ssu_gui::install_mani()
{
    installMani *mani = new installMani(this);

    mani->exec();

    delete mani;
}

void ssu_gui::switchLanguage()
{

    bool ok;

    QString i = QInputDialog::getItem(this, tr("Change Language"), tr("Please choose your favorite language"), QStringList() << "default" << "English" << "Deutsch", 0, false, &ok);

    if(!ok)
        return;

    QSettings settings("MJ", "ssu_gui");

    settings.setValue("lang", i);

    QMessageBox::information(this, tr("Restart required"), tr("Please restart ssu_gui now to make the Language changes effect!\nThank you!"), QMessageBox::Ok | QMessageBox::Default);
}

void ssu_gui::copyMaps()
{
    cpMaps *cpM = new cpMaps(this);

    cpM->exec();

    delete cpM;
}
 
void ssu_gui::setWorkSpace()
{
    setWSpace *wspace = new setWSpace(this);

    wspace->exec();

    delete wspace;
}

void ssu_gui::openDbgConsole()
{
    dbgConsole->show();
}
